/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

package org.netbeans.modules.db.explorer.dlg;

import java.awt.BorderLayout;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;

import javax.swing.event.DocumentListener;
import javax.swing.event.ListDataListener;
import org.netbeans.api.progress.ProgressHandle;
import org.netbeans.api.progress.ProgressHandleFactory;

import org.openide.util.NbBundle;

import org.netbeans.modules.db.explorer.DatabaseConnection;

public class ConnectPanel extends ConnectionDialog.FocusablePanel implements DocumentListener, ListDataListener {

    private ProgressHandle progressHandle;
    private JComponent progressComponent;

    /**
     * Creates new form ConnectPanel
     * 
     * @param connection instance of DatabaseConnection object
     */
    @SuppressWarnings("LeakingThisInConstructor")
    public ConnectPanel(ConnectionDialogMediator mediator, DatabaseConnection connection) {
        initComponents();
        initAccessibility();

        ConnectionProgressListener progressListener = new ConnectionProgressListener() {
            @Override
            public void connectionStarted() {
                startProgress();
            }
            
            @Override
            public void connectionStep(String step) {
                setProgressMessage(step);
            }

            @Override
            public void connectionFinished() {
                stopProgress(true);
            }

            @Override
            public void connectionFailed() {
                stopProgress(false);
            }
        };
        mediator.addConnectionProgressListener(progressListener);

        userTextField.setText(connection.getUser());
        if (connection.rememberPassword()) {
            passwordField.setText(connection.getPassword());
            passwordCheckBox.setSelected(true);
        }

        userTextField.getDocument().addDocumentListener(this);
        passwordField.getDocument().addDocumentListener(this);
    }

    private void initAccessibility() {
        userLabel.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage (ConnectPanel.class, "ACS_ConnectDialogUserNameA11yDesc")); //NOI18N
        userTextField.getAccessibleContext().setAccessibleName(NbBundle.getMessage (ConnectPanel.class, "ACS_ConnectDialogUserNameTextFieldA11yName")); //NOI18N
        passwordLabel.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage (ConnectPanel.class, "ACS_ConnectDialogPasswordA11yDesc")); //NOI18N
        passwordField.getAccessibleContext().setAccessibleName(NbBundle.getMessage (ConnectPanel.class, "ACS_ConnectDialogPasswordTextFieldA11yName")); //NOI18N
        connectProgressPanel.getAccessibleContext().setAccessibleName(NbBundle.getMessage (ConnectPanel.class, "ACS_ConnectionProgressBarA11yName")); //NOI18N
        connectProgressPanel.getAccessibleContext().setAccessibleDescription(NbBundle.getMessage (ConnectPanel.class, "ACS_ConnectionProgressBarA11yDesc")); //NOI18N
    }

    @Override
    public void initializeFocus() {
        getInitiallyFocusedComponent().requestFocusInWindow();
    }

    private JComponent getInitiallyFocusedComponent() {
        if (userTextField.getText().length() == 0) {
            return userTextField;
        }
        if (passwordField.getPassword().length == 0) {
            return passwordField;
        }
        // fall back to the user field
        return userTextField;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        userLabel = new javax.swing.JLabel();
        passwordLabel = new javax.swing.JLabel();
        passwordCheckBox = new javax.swing.JCheckBox();
        passwordField = new javax.swing.JPasswordField();
        userTextField = new javax.swing.JTextField();
        connectProgressPanel = new javax.swing.JPanel();
        progressMessageLabel = new javax.swing.JLabel();
        progressContainerPanel = new javax.swing.JPanel();

        setLayout(new java.awt.GridBagLayout());

        userLabel.setLabelFor(userTextField);
        org.openide.awt.Mnemonics.setLocalizedText(userLabel, org.openide.util.NbBundle.getMessage(ConnectPanel.class, "ConnectDialogUserName")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(12, 12, 0, 0);
        add(userLabel, gridBagConstraints);

        passwordLabel.setLabelFor(passwordField);
        org.openide.awt.Mnemonics.setLocalizedText(passwordLabel, org.openide.util.NbBundle.getMessage(ConnectPanel.class, "ConnectDialogPassword")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 12, 0, 0);
        add(passwordLabel, gridBagConstraints);

        org.openide.awt.Mnemonics.setLocalizedText(passwordCheckBox, org.openide.util.NbBundle.getMessage(ConnectPanel.class, "ConnectDialogRememberPassword")); // NOI18N
        passwordCheckBox.setToolTipText(org.openide.util.NbBundle.getMessage(ConnectPanel.class, "ACS_ConnectDialogRememberPasswordA11yDesc")); // NOI18N
        passwordCheckBox.setVerticalTextPosition(javax.swing.SwingConstants.TOP);
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 2;
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.WEST;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 11);
        add(passwordCheckBox, gridBagConstraints);

        passwordField.setToolTipText(org.openide.util.NbBundle.getMessage(ConnectPanel.class, "ACS_ConnectDialogPasswordTextFieldA11yDesc")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 1;
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(5, 5, 0, 11);
        add(passwordField, gridBagConstraints);

        userTextField.setToolTipText(org.openide.util.NbBundle.getMessage(ConnectPanel.class, "ACS_ConnectDialogUserNameTextFieldA11yDesc")); // NOI18N
        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 1;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.insets = new java.awt.Insets(12, 5, 0, 11);
        add(userTextField, gridBagConstraints);

        connectProgressPanel.setToolTipText(org.openide.util.NbBundle.getMessage(ConnectPanel.class, "ACS_ConnectionProgressBarA11yDesc")); // NOI18N
        connectProgressPanel.setLayout(new java.awt.BorderLayout(0, 5));

        org.openide.awt.Mnemonics.setLocalizedText(progressMessageLabel, " ");
        connectProgressPanel.add(progressMessageLabel, java.awt.BorderLayout.NORTH);

        progressContainerPanel.setMinimumSize(new java.awt.Dimension(20, 20));
        progressContainerPanel.setPreferredSize(new java.awt.Dimension(20, 20));
        progressContainerPanel.setLayout(new java.awt.BorderLayout());
        connectProgressPanel.add(progressContainerPanel, java.awt.BorderLayout.CENTER);

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 3;
        gridBagConstraints.gridwidth = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.gridheight = java.awt.GridBagConstraints.REMAINDER;
        gridBagConstraints.fill = java.awt.GridBagConstraints.HORIZONTAL;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.SOUTH;
        gridBagConstraints.weightx = 1.0;
        gridBagConstraints.weighty = 1.0;
        gridBagConstraints.insets = new java.awt.Insets(12, 12, 11, 11);
        add(connectProgressPanel, gridBagConstraints);
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel connectProgressPanel;
    private javax.swing.JCheckBox passwordCheckBox;
    private javax.swing.JPasswordField passwordField;
    private javax.swing.JLabel passwordLabel;
    private javax.swing.JPanel progressContainerPanel;
    private javax.swing.JLabel progressMessageLabel;
    private javax.swing.JLabel userLabel;
    private javax.swing.JTextField userTextField;
    // End of variables declaration//GEN-END:variables

    public String getUser() {
        return userTextField.getText();
    }

    public String getPassword() {
        return String.valueOf(passwordField.getPassword());
    }
	
	public void showRememberPasswordOption(boolean flag) {
		passwordCheckBox.setVisible(flag);
	}

    public boolean rememberPassword() {
        return passwordCheckBox.isSelected();
    }

    public String getTitle() {
        return NbBundle.getMessage (ConnectPanel.class, "ConnectDialogTitle"); // NOI18N
    }

    private void startProgress() {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                progressHandle = ProgressHandle.createHandle(null);
                progressComponent = ProgressHandleFactory.createProgressComponent(progressHandle);
                progressContainerPanel.add(progressComponent, BorderLayout.CENTER);
                progressHandle.start();
                progressMessageLabel.setText(NbBundle.getMessage (ConnectPanel.class, "ConnectionProgress_Connecting"));
            }
        });
    }
    
    private void setProgressMessage(final String message) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                progressMessageLabel.setText(message);
            }
        });
    }

    private void stopProgress(final boolean connected) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                if (progressHandle == null) {
                    return ;
                }
                progressHandle.finish();
                progressContainerPanel.remove(progressComponent);
                // without this, the removed progress component remains painted on its parent... why?
                progressContainerPanel.repaint();
                if (connected) {
                    progressMessageLabel.setText(NbBundle.getMessage (ConnectPanel.class, "ConnectionProgress_Established"));
                } else {
                    progressMessageLabel.setText(NbBundle.getMessage (ConnectPanel.class, "ConnectionProgress_Failed"));
                }
            }
        });
    }
    
    private void resetProgress() {
        progressMessageLabel.setText(""); // NOI18N
    }

    @Override
    public void changedUpdate(javax.swing.event.DocumentEvent e) {
        fireChange();
    }

    @Override
    public void insertUpdate(javax.swing.event.DocumentEvent e) {
        fireChange();
    }

    @Override
    public void removeUpdate(javax.swing.event.DocumentEvent e) {
        fireChange();
    }

    @Override
    public void contentsChanged(javax.swing.event.ListDataEvent e) {
        fireChange();
    }

    @Override
    public void intervalAdded(javax.swing.event.ListDataEvent e) {
        fireChange();
    }

    @Override
    public void intervalRemoved(javax.swing.event.ListDataEvent e) {
        fireChange();
    }

    private void fireChange() {
        firePropertyChange("argumentChanged", null, null);
        resetProgress();
    }
}
